package com.demoview.test.myapplication.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.demoview.test.myapplication.MessageBean;
import com.demoview.test.myapplication.R;
import com.demoview.test.myapplication.SingleSocket;
import com.demoview.test.myapplication.User;

import com.demoview.test.myapplication.adapter.MsgsAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.socket.client.Socket;
import io.socket.emitter.Emitter;

public class MessageActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = "MessageActivityxxxxxxx";
    private Socket mSocket;
    private RecyclerView mRecyclerView;
    private MsgsAdapter mAdapter;
    private MessageBean msgBean;
    private List<User> mMsgs = new ArrayList<>();
    private EditText mEditText;
    @SuppressLint("WrongConstant")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        //获取服务器地址
        getServerUrl();
        mRecyclerView = findViewById(R.id.messages);
        mEditText = findViewById(R.id.message_input);
        findViewById(R.id.send_button).setOnClickListener(this);


        mRecyclerView.setLayoutManager(new LinearLayoutManager(MessageActivity.this,LinearLayoutManager.VERTICAL,false));
        mAdapter = new MsgsAdapter(R.layout.item_msg,mMsgs);
        mRecyclerView.setAdapter(mAdapter);

    }

    private Emitter.Listener broadcastingListener = new Emitter.Listener() {
        @SuppressLint("WrongConstant")
        @Override
        public void call(Object... args) {
            JSONArray data = (JSONArray) args[0];
            Log.d(TAG,data.toString());
            System.out.print(data.toString());


            for (int i=0;i<data.length();i++){
                try {
                    String a= data.getString(i);
                    Log.d(TAG,a);
                    JSONObject jsonObject=new JSONObject(a);
                    JSONArray jsonArray=jsonObject.getJSONArray("msg");
                    for (int s=0;s<jsonArray.length();s++){
                        String method=jsonArray.getJSONObject(s).getString("_method_");
                        String type=jsonArray.getJSONObject(s).getString("msgtype");
                        if ("SendMsg".equals(method)&& "2".equals(type)){
                            String ct=jsonArray.getJSONObject(s).getString("ct");
                            String uname=jsonArray.getJSONObject(s).getString("uname");
                            updateUI(new User(uname,": "+ct));

                        }
                    }





                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        mSocket.disconnect();
        mSocket.off("broadcastingListen",broadcastingListener);
        mSocket.off(Socket.EVENT_CONNECT);
    }

    /**
     * 获取服务器地址
     */
    private void getServerUrl(){
        OkGo.<String>get("https://livenew.yunbaozb.com/appapi/?service=Live.enterRoom")
                .params("uid", "46390")
                .params("token", "e00a89db593dbac0fa78ec0b1fccb6f0")
                .params("city", "%E6%B3%B0%E5%AE%89%E5%B8%82")
                .params("liveuid", "34043")
                .params("mobileid", "811fd947e528b51f6d1687c766a194d4")
                .params("stream", "34043_1627468319")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        System.out.print("成功==" + response);
                        mSocket = SingleSocket.getInstance().getSocket();

                        //注册 login 事件
                        mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
                            @Override
                            public void call(Object... args) {
                                Log.d(TAG, "zsr call: ");
                                org.json.JSONObject data=new org.json.JSONObject();
                                try {
                                    data.put("uid","46390");
                                    data.put("token","e00a89db593dbac0fa78ec0b1fccb6f0");
                                    data.put("mobileid","811fd947e528b51f6d1687c766a194d4");
                                    data.put("liveuid","34043");
                                    data.put("roomnum","34043");
                                    data.put("stream","34043_1627468319");

                                    //发送
                                    mSocket.emit("conn",data);

                                }catch(JSONException e){
                                    e.printStackTrace();
                                }

                            }
                        });

                        mSocket.on("broadcastingListen",broadcastingListener);
                        mSocket.connect();


                    }

                });

    }

    private void updateUI(final User user){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mMsgs.add(user);
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onClick(View v) {
        String message = mEditText.getText().toString().trim();

        Map<String,Object> map=new HashMap<>();
        Map<String,Object> json=new HashMap<>();
        List<Map<String ,Object>> msg=new ArrayList<>();
        map.put("_method_","SendMsg");
        map.put("action",0);
        map.put("ct",message);
        map.put("msgtype","2");
        map.put("tougood","");
        map.put("touid","");
        map.put("touname","");
        map.put("ugood","SendMsg");
        map.put("uid","46390");
        map.put("uname","手机用户8887");
        map.put("level","1");
        map.put("vip_type","0");
        map.put("liangname","0");
        map.put("usertype","30");
        map.put("guard_type","0");
        msg.add(map);

        json.put("retcode","000000");
        json.put("retmsg","OK");
        json.put("msg",msg);
        Gson gson = new Gson();
        String value = gson.toJson(json);
        mSocket.emit("broadcast", value);
        mEditText.setText("");
        mEditText.requestFocus();


    }


}
